<template>
    <div>
        <el-form label-width="6rem">
            <el-form-item label="SKU名称">
                <el-input placeholder="SKU名称" v-model="skuParams.skuName"></el-input>
            </el-form-item>
            <el-form-item label="价格（元）">
                <el-input placeholder="价格（元）" type="number" v-model="skuParams.price"></el-input>
            </el-form-item>
            <el-form-item label="重量（克）">
                <el-input placeholder="重量（克）" type="number" v-model="skuParams.weight"></el-input>
            </el-form-item>
            <el-form-item label="SKU描述">
                <el-input placeholder="SKU描述" type="textarea" v-model="skuParams.skuDesc"></el-input>
            </el-form-item>
            <el-form-item label="平台属性">
                <el-form :inline="true" label-width="6rem">
                    <el-form-item v-for="(item, index) in attrArr" :key="item.id" :label="item.attrName">
                        <el-select style="width: 13rem; margin: 0 .5rem" v-model="item.attrIdAndValueId">
                            <el-option v-for="(attrValue, index) in item.attrValueList" :key="attrValue.id"
                                :value="`${item.id}: ${attrValue.id}`" :label="attrValue.valueName"></el-option>
                        </el-select>
                    </el-form-item>
                </el-form>
            </el-form-item>
            <el-form-item label="销售属性">
                <el-form :inline="true" label-width="6rem">
                    <el-form-item v-for="(item, index) in saleAttr" :key="item.id" :label="item.saleAttrName">
                        <el-select style="width: 13rem; margin: 0 .5rem" v-model="item.saleIdAndValueId">
                            <el-option v-for="(saleAttrValue, index) in item.spuSaleAttrValueList"
                                :key="saleAttrValue.id" :value="`${item.id}: ${saleAttrValue.id}`"
                                :label="saleAttrValue.saleAttrValueName"></el-option>
                        </el-select>
                    </el-form-item>
                </el-form>
            </el-form-item>
            <el-form-item label="图片名称">
                <el-table border :data="imgList" ref="table">
                    <el-table-column type="selection" width="80px" align="center"></el-table-column>
                    <el-table-column label="图片">
                        <template #="{ row, $index }">
                            <img :src="row.imgUrl" style="width: 8rem; height: 8rem;">
                        </template>
                    </el-table-column>
                    <el-table-column label="名称" prop="imgName"></el-table-column>
                    <el-table-column label="操作">
                        <template #="{ row, $index }">
                            <el-button type="primary" size="small" @click="handler(row)">设置默认</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" size="default" @click="save">保存</el-button>
                <el-button type="primary" size="default" @click="cancle">取消</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script setup lang="ts">
import type { SpuData, SaleAttr, SaleAttrResponseData, SpuImg, SpuHasImg, SkuData } from '@/api/product/spu/type'
import type { Attr, AttrResponseData } from '@/api/product/attr/type'
import { reqAttr } from '@/api/product/attr'
import { reqSpuImageList, reqSpuHasSaleAttr, reqAddSku } from '@/api/product/spu'
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'

let $emit = defineEmits(['changeScene'])
//存储已有的平台属性
let attrArr = ref<Attr[]>([])
//存储已有的销售属性
let saleAttr = ref<SaleAttr[]>([])
//存储已有的照片墙数据
let imgList = ref<SpuImg[]>([])
//收集SKU的参数
let skuParams = reactive<SkuData>({
    category3Id: "",
    spuId: "",
    tmId: "",
    skuName: "",
    price: "",
    weight: "",
    skuDesc: "",
    skuAttrVallueList: [],
    skuSaleAttrValueList: [],
    skuDefaultImg: ""
})
//获取table组件实例
let table = ref<any>()

//点击保存按钮
const save = async () => {
    //整理参数
    //平台属性
    skuParams.skuAttrVallueList = attrArr.value.reduce((prev: any, next: any) => {
        if (next.attrIdAndValueId) {
            let [attrId, valueId] = next.attrIdAndValueId.split(':')
            prev.push([attrId, valueId])
        }
        return prev
    }, [])
    //销售属性
    skuParams.skuSaleAttrValueList = saleAttr.value.reduce((prev: any, next: any) => {
        if (next.saleIdAndValueId) {
            let [saleAttrId, saleAttrValueId] = next.saleIdAndValueId.split(':')
            prev.push([saleAttrId, saleAttrValueId])
        }
        return prev
    }, [])
    //发请求
    let result: any = await reqAddSku(skuParams)
    if (result.code == 200) {
        ElMessage({
            type: 'success',
            message: '添加SKU成功'
        })
        $emit('changeScene', { flag: 0, params: '' })
    } else {
        ElMessage({
            type: 'error',
            message: '添加SKU失败'
        })
    }
}
//点击取消按钮，通知父组件切换场景为1，展示已有的SPU数据
const cancle = () => {
    $emit('changeScene', { flag: 0, params: '' })
}
//当前子组件的方法对外暴露
const initSkuData = async (c1Id: number | string, c2Id: number | string, spu: SpuData) => {
    //收集数据
    skuParams.category3Id = spu.category3Id
    skuParams.spuId = (spu.id as number)
    skuParams.tmId = spu.tmId
    //获取平台属性
    let result1: AttrResponseData = await reqAttr(c1Id, c2Id, spu.category3Id)
    //获取销售属性
    let result2: SaleAttrResponseData = await reqSpuHasSaleAttr((spu.id as number))
    //获取照片墙数据
    let result3: SpuHasImg = await reqSpuImageList((spu.id as number))

    //储存数据
    attrArr.value = result1.data
    saleAttr.value = result2.data
    imgList.value = result3.data
}
//设置默认图片的方法回调
const handler = (row: any) => {
    //点击的时候，全部复选框不选
    imgList.value.forEach(item => {
        //复选框全不选中
        table.value.toggleRowSelection(item, false)
    })
    //复选框选中
    table.value.toggleRowSelection(row, true)
    //收集默认图片地址
    skuParams.skuDefaultImg = row.imgUrl
}

defineExpose({
    initSkuData
})
</script>

<style scoped lang="scss"></style>